let xlsxrd = require('node-xlsx');
var fs = require('fs');
var join = require('path').join;

// var filesPath = 'excel';
var ExcelToJson = function () {

}
var pro = ExcelToJson.prototype;

pro.getRealValue = function (dType,value) {
    if (!!value){
        return value;
    }
    return '';
}

pro.sheetToJson = function(sheet) {
    var keys = sheet[0];//第一行是key
    var flags = sheet[1];//要不要输出
    var types = sheet[3];//第三行是数据类型
    var data = [];
    var isSomethingOutput = false;
    for (var i=0;i<flags.length;i++){
        var flag = flags[i];
        if (flag === 'C' || flag === 'a'){
            isSomethingOutput = true;
            break;
        }
    }
    if (!isSomethingOutput){//没有客户端要的内容，那么不输出json
        return data;
    }

    //第5行开始则是数据
    var idx = 5;
    while (idx<sheet.length){
        var object = {};
        let isOk = true;
        var lineData = sheet[idx];
        for (var i=0;i<keys.length;i++){
            var flagTmp = flags[i];
            if (!!keys[i] && (flagTmp === 'C' || flagTmp === 'a')){
                var key = keys[i];
                var dType = types[i];
                var value = lineData[i];
                if (!value && i === 0){
                    isOk = false;
                }
                var realValue =  this.getRealValue(dType,value);
                object[key] = realValue;
            }
        }
        if (isOk){
            var keyTmps = Object.keys(object);
            if(keyTmps.length>1){
                data.push(object);
            }
        }
        idx++;
    }
    return data;
}

pro.excelToJson = function (filePath) {
    let self = this;
    let sheets = xlsxrd.parse(filePath);
    for (var i = 0; i < sheets.length; i++){
        var sheet = sheets[i];
        var sheetName = sheet.name;
        if (sheetName.indexOf('Sheet')>-1||sheetName.indexOf(' ')>-1){//Sheet 非法sheet名字
            continue;
        }
        var data = sheet.data
        let reg = /[\u4e00-\u9fa5]/g;
        let regResult = sheetName.match(reg);
        if (!regResult){
            var jsonData = this.sheetToJson(data);//页签转json
            if (jsonData.length > 0){
                var outputFile = self.ouputPath +'/'+sheetName+'.json';
                //合并Json
                fs.writeFileSync(outputFile, JSON.stringify(jsonData));
                console.log(outputFile);
            }
        }
    }
}

pro.loadExcel = function (filesPath,ouputPath){
    var fileOuput = {};
    var self = this;
    self.ouputPath = ouputPath;
    let files = fs.readdirSync(filesPath);
    files.forEach(function (item, index) {
        let fPath = join(filesPath,item);
        let stat = fs.statSync(fPath);
        if (stat.isFile() === true && item.indexOf('.xlsx') > 0) {
            var filePath = filesPath+'/'+item;
            self.excelToJson(filePath);
            console.log(filePath)
        }
    });
}

module.exports = new ExcelToJson();